package cn.iocoder.yudao.module.call.controller.admin.channel;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.call.controller.admin.channel.vo.ChannelPageReqVO;
import cn.iocoder.yudao.module.call.controller.admin.channel.vo.ChannelRespVO;
import cn.iocoder.yudao.module.call.controller.admin.channel.vo.ChannelSaveReqVO;
import cn.iocoder.yudao.module.call.dal.dataobject.channel.ChannelDO;
import cn.iocoder.yudao.module.call.service.channel.ChannelService;
import cn.iocoder.yudao.module.call.service.okcctocm.OkccToCmService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "呼叫中心 - 外呼渠道")
@RestController
@RequestMapping("/call/channel")
@Validated
@Slf4j
public class ChannelController {

    @Resource
    private ChannelService channelService;

    @Resource
    private OkccToCmService okccToCmService;


    @PostMapping("/create")
    @Operation(summary = "创建外呼渠道")
    @PreAuthorize("@ss.hasPermission('call:channel:create')")
    public CommonResult<Long> createChannel(@Valid @RequestBody ChannelSaveReqVO createReqVO) {
        return success(channelService.createChannel(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新外呼渠道")
    @PreAuthorize("@ss.hasPermission('call:channel:update')")
    public CommonResult<Boolean> updateChannel(@Valid @RequestBody ChannelSaveReqVO updateReqVO) {
        channelService.updateChannel(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除外呼渠道")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('call:channel:delete')")
    public CommonResult<Boolean> deleteChannel(@RequestParam("id") Long id) {
        channelService.deleteChannel(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得外呼渠道")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('call:channel:query')")
    public CommonResult<ChannelRespVO> getChannel(@RequestParam("id") Long id) {
        ChannelDO channel = channelService.getChannel(id);
        return success(BeanUtils.toBean(channel, ChannelRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得外呼渠道分页")
    @PreAuthorize("@ss.hasPermission('call:channel:query')")
    public CommonResult<PageResult<ChannelRespVO>> getChannelPage(@Valid ChannelPageReqVO pageReqVO) {
        PageResult<ChannelDO> pageResult = channelService.getChannelPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ChannelRespVO.class));
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获得外呼渠道列表")
    public CommonResult<List<ChannelRespVO>> getChannelList() {
        ChannelPageReqVO pageReqVO = new ChannelPageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ChannelDO> list = channelService.getChannelPage(pageReqVO).getList();
        return success(BeanUtils.toBean(list, ChannelRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出外呼渠道 Excel")
    @PreAuthorize("@ss.hasPermission('call:channel:export')")
    @OperateLog(type = EXPORT)
    public void exportChannelExcel(@Valid ChannelPageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ChannelDO> list = channelService.getChannelPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "外呼渠道.xls", "数据", ChannelRespVO.class,
                BeanUtils.toBean(list, ChannelRespVO.class));
    }

    @GetMapping("/get-sip-mode")
    @Operation(summary = "获取当前sip软电话模式")
    public CommonResult<String> getSipMode() {
        String sipMode = channelService.getSipMode(TenantContextHolder.getTenantId());
        return success(sipMode);
    }

    @PostMapping("/okcc-to-cm")
    @OperateLog(enable = false)
    public CommonResult<List<Long>> okccToCm(@RequestBody Map<String, Object> params) {
        Object tenantIdsObj = params.get("tenantIds");
        List<Long> tenantIds = new ArrayList<>();
        for (Object item : (List<?>) tenantIdsObj) {
            if (item instanceof Number) {
                tenantIds.add(((Number) item).longValue());
            } else if (item instanceof String) {
                try {
                    tenantIds.add(Long.parseLong((String) item));
                } catch (NumberFormatException e) {
                    // 忽略无法转换的项或记录日志
                    log.warn("无法转换为Long类型的值: {}", item);
                }
            }
        }

        List<Long> successList = new ArrayList<>();
        log.info("[okccToCM]开始转换:{}", params);
        for (Long tenantId : tenantIds) {
            try {
                okccToCmService.migrate(tenantId);
                successList.add(tenantId);
            } catch (Exception e) {
                log.error("[okccToCM]租户转换异常:{}", tenantId, e);
            }
        }
        return success(successList);
    }


}